package com.gxar.quick.ar.server.base.factory;

import com.gxar.common.exception.APIRuntimeException;
import com.gxar.quick.ar.server.base.common.enums.protocol.ArProtocolEditorEnum;
import com.gxar.quick.ar.server.base.model.ResultCodeEnum;
import com.gxar.quick.ar.server.base.model.protocol.editor.EditorArProtocol;
import com.gxar.quick.ar.server.base.model.protocol.editor.unity.UnityEditorArProtocol;
import com.gxar.quick.ar.server.base.model.protocol.editor.web.WebEditorArProtocol;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 编辑器协议工厂
 *
 * @author zxh
 * @version 1.0
 * @created 2024/02/23.
 */
@Component
public class EditorArProtocolFactory {

    private final Map<ArProtocolEditorEnum, Class<? extends EditorArProtocol>> protocolsMap = new ConcurrentHashMap<>();

    public EditorArProtocolFactory() {
        protocolsMap.put(ArProtocolEditorEnum.WEB_EDITOR, WebEditorArProtocol.class);
        protocolsMap.put(ArProtocolEditorEnum.UNITY_EDITOR, UnityEditorArProtocol.class);
    }


    /**
     * 创建实例
     *
     * @param editor 编辑器类型
     * @return
     */
    public EditorArProtocol create(ArProtocolEditorEnum editor) {
        Class<? extends EditorArProtocol> editorProtocol = protocolsMap.getOrDefault(editor, null);
        if (Objects.isNull(editorProtocol)) {
            throw new APIRuntimeException(ResultCodeEnum.CONVERT_EDITOR_PROTOCOL_FAILED);
        }

        EditorArProtocol protocolInstance = null;
        try {
            protocolInstance = editorProtocol.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new APIRuntimeException(ResultCodeEnum.CONVERT_EDITOR_PROTOCOL_FAILED);
        }

        return protocolInstance;
    }
}
